//
//  DateSelectionView.m
//  DateSelectionView
//
//  Created by LiTengFei on 15/3/6.
//  Copyright (c) 2015年 LiTengFei. All rights reserved.
//

#import "DateSelectionView.h"
@interface DateSelectionView () <UITableViewDataSource,UITableViewDelegate>

@property (nonatomic,strong) UITableView * dateTableView;
@property (nonatomic,strong) UITableView * timeTableView;

@property (nonatomic,strong) NSMutableArray * dateDataArray;
@property (nonatomic,strong) NSMutableArray * timeDataArray;


@property (nonatomic,strong) CALayer * dateLayer;
@property (nonatomic,strong) CALayer * timeLayer;

@property (nonatomic,strong) CALayer * centerLayer;
@end

static CGFloat cell_height = 35;

@implementation DateSelectionView

-(instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if(self){
        [self commonInstance];
    }
    return self;
}
- (void)dataInstance {

    _dateDataArray = [[NSMutableArray alloc]initWithCapacity:0];
    _dateDataArray = [self dateArrayAfterNow];

    _timeDataArray = [[NSMutableArray alloc]initWithCapacity:0];
    _timeDataArray = [self timeArrayInDate:[NSDate date]];

    _selectedDate = ({
        NSDate * date = [NSDate date];
        NSDateFormatter * dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"MM月dd日"];
        NSString * dateString = [dateFormatter stringFromDate:date];
        dateString;
    });

    _selectedTime = ({
        NSString * timeString = @"00:00";
        timeString;
    });
}

-(void)setCurrentDate:(NSDate *)currentDate{
    _currentDate = currentDate;
}

-(NSMutableArray *)dateArrayAfterNow{
//    NSDate * currentDate = [NSDate date];
    NSMutableArray * array = [[NSMutableArray alloc]initWithCapacity:0];

    NSCalendar *calendar = [[NSCalendar alloc]initWithCalendarIdentifier:@"calendar"];

    for (int i = 0; i < 20; i++) {
        NSDate * currentDate2 = [[NSDate date] dateByAddingTimeInterval:i*60*60*24];
        NSDateFormatter * dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"MM月dd日"];
        NSString * dateString = [dateFormatter stringFromDate:currentDate2];
        [array addObject:dateString];
    }
    return array;
}

-(NSMutableArray *)timeArrayInDate:(NSDate *)date{
//    NSDate * currentDate = [[NSDate alloc]init];
    NSMutableArray * array = [[NSMutableArray alloc]initWithCapacity:0];
//    NSCalendar * calendar = [[NSCalendar alloc]init];
    NSInteger index = 0;
    for (int i = 0; i < 48; i++) {
        index = 30 * i;
//        NSDate * currentDate2 = [[[NSDate alloc]init] dateByAddingTimeInterval:i*60*30];
//        NSDateFormatter * dateFormatter = [[NSDateFormatter alloc] init];
//        [dateFormatter setDateFormat:@"几点几分"];
//        NSString * dateString = [dateFormatter stringFromDate:currentDate];
        NSString * time = [NSString stringWithFormat:@"%.2ld:%.2ld", (long)index / 60 , (long)index % 60 ];
        [array addObject:time];
    }
    return array;
}

-(void)commonInstance{

    [self dataInstance];

    CGRect dateFrame = CGRectMake(0, 0, CGRectGetWidth(self.frame) / 2,CGRectGetHeight(self.frame));
    self.dateTableView = [[UITableView alloc]initWithFrame:dateFrame style:UITableViewStylePlain];
    self.dateTableView.delegate = self;
    self.dateTableView.dataSource = self;
    self.dateTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.dateTableView.showsHorizontalScrollIndicator =NO;
    self.dateTableView.showsVerticalScrollIndicator = NO;
    [self addSubview:self.dateTableView];

    CGRect timeFrame = CGRectMake(CGRectGetWidth(self.frame)/2, 0, CGRectGetWidth(self.frame) / 2 ,CGRectGetHeight(self.frame));
    self.timeTableView = [[UITableView alloc]initWithFrame:timeFrame style:UITableViewStylePlain];
    self.timeTableView.delegate = self;
    self.timeTableView.dataSource = self;
    self.timeTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.timeTableView.showsVerticalScrollIndicator = NO;
    self.timeTableView.showsHorizontalScrollIndicator = NO;
    [self addSubview:self.timeTableView];

//    [self separatorLayerWithFrame:CGRectZero];
//    [self separatorLayer];

    _centerLayer = [[CALayer alloc]init];
    _centerLayer.frame = CGRectMake(CGRectGetWidth(self.dateTableView.frame) - 0.5, 8.5, 1, CGRectGetHeight(self.frame) - 17);
    _centerLayer.backgroundColor = [UIColor lightGrayColor].CGColor;
    [self.layer addSublayer:_centerLayer];
}
-(void)setDelegate:(id<DateSelectionDelegate>)delegate{
    _delegate = delegate;
    if(self.delegate &&[self.delegate respondsToSelector:@selector(dateSelectionView:updateSelectedDate:updateSelectedTime:)]){
        [self.delegate dateSelectionView:self updateSelectedDate:self.selectedDate updateSelectedTime:self.selectedTime];
    }
}
-(CGFloat)topSpaceHeight{
    return (CGRectGetHeight(self.dateTableView.frame) - cell_height) / 2;
}

-(CALayer *)separatorLayer{
//    CGFloat default_space = 5;

    CALayer * topLayer;
    topLayer = [[CALayer alloc]init];
    topLayer.frame = CGRectMake(0, 0, CGRectGetWidth(self.frame) , (CGRectGetHeight(self.dateTableView.frame) - cell_height) / 2);
    topLayer.backgroundColor = [UIColor colorWithWhite:0 alpha:0.1].CGColor;
//    topLayer.borderWidth = 1;

    [self.layer addSublayer:topLayer];

    CALayer * bottomLayer;
    bottomLayer = [[CALayer alloc]init];
    bottomLayer.frame = CGRectMake(0, (CGRectGetHeight(self.dateTableView.frame) + cell_height) / 2, CGRectGetWidth(self.frame) , (CGRectGetHeight(self.dateTableView.frame) - cell_height) / 2);
//    bottomLayer.borderColor = [UIColor lightGrayColor].CGColor;
//    bottomLayer.borderWidth = 1;
    bottomLayer.backgroundColor = [UIColor colorWithWhite:0 alpha:0.1].CGColor;
    [self.layer addSublayer:bottomLayer];
    return nil;
}

-(CALayer *)separatorLayerWithFrame:(CGRect) frame{
    CGFloat default_space = 5;
    CALayer * topLayer;
    topLayer = [[CALayer alloc]init];
    topLayer.frame = CGRectMake(default_space, (CGRectGetHeight(self.dateTableView.frame) - cell_height) / 2, CGRectGetWidth(self.frame) - 2 * default_space , 1);
    topLayer.borderColor = [UIColor lightGrayColor].CGColor;
    topLayer.borderWidth = 1;

    [self.layer addSublayer:topLayer];

    CALayer * bottomLayer;
    bottomLayer = [[CALayer alloc]init];
    bottomLayer.frame = CGRectMake(default_space, (CGRectGetHeight(self.dateTableView.frame) + cell_height) / 2, CGRectGetWidth(self.frame) - 2 * default_space , 1);
    bottomLayer.borderColor = [UIColor lightGrayColor].CGColor;
    bottomLayer.borderWidth = 1;
    [self.layer addSublayer:bottomLayer];
    return nil;
}

#pragma mark - table view delegate

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if(tableView==self.dateTableView){
        UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"dateTableCell"];
        if(cell == nil){
            cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"dateTableCell"];
            cell.textLabel.textAlignment = NSTextAlignmentCenter;
            cell.textLabel.font  = [UIFont systemFontOfSize:14.0];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        NSString * dateString = [self.dateDataArray objectAtIndex:indexPath.row];
        cell.textLabel.text = dateString;
        return cell;
    }else if (tableView==_timeTableView){
        UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"timeTableCell"];
        if(cell == nil){
            cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"timeTableCell"];
            cell.textLabel.textAlignment = NSTextAlignmentCenter;
            cell.textLabel.font = [UIFont systemFontOfSize:14.0];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        NSString * timeString = [self.timeDataArray objectAtIndex:indexPath.row];
        cell.textLabel.text = timeString;
        return cell;
    }
    return nil;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if(tableView == _dateTableView){
        return self.dateDataArray.count;
    }
    if(tableView == _timeTableView){
        return self.timeDataArray.count;
    }
    return 0;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return cell_height;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    CGFloat table_header_height = (CGRectGetHeight(self.frame) - cell_height) / 2;
    return table_header_height;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    CGFloat table_header_height = (CGRectGetHeight(self.frame) - cell_height) / 2;
    return table_header_height;
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    CGFloat table_header_height = (CGRectGetHeight(self.frame) - cell_height) / 2;
    return [[UIView alloc]initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.frame), table_header_height)];
}
-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    CGFloat table_header_height = (CGRectGetHeight(self.frame) - cell_height) / 2;
    return [[UIView alloc]initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.frame), table_header_height)];
}

#pragma mark - scrool view delegate

-(void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    NSLog(@"%@",NSStringFromCGPoint(scrollView.contentOffset));

    CGFloat scale = scrollView.contentOffset.y / cell_height;

    NSInteger a = (NSInteger)scale;
    NSInteger b = a + 1;
    NSInteger c = (b - scale) >(scale - a) ? a : b;
    NSLog(@"%ld",c);

    if([scrollView isEqual:self.dateTableView]){
        if(c >= self.dateDataArray.count ){
            c = self.dateDataArray.count - 1;
        }
        if(c < 0){
            c = 0;
        }
        _selectedDate = [self.dateDataArray objectAtIndex:c];
    }
    if([scrollView isEqual:self.timeTableView]){
        if(c >= self.timeDataArray.count ){
            c = self.timeDataArray.count - 1;
        }
        if(c < 0){
            c = 0;
        }
        _selectedTime = [self.timeDataArray objectAtIndex:c];
    }
    [UIView animateWithDuration:0.3 animations:^{
        scrollView.contentOffset = CGPointMake(0, c * cell_height);
    }];
}

-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    NSLog(@"%@",NSStringFromCGPoint(scrollView.contentOffset));
    CGFloat scale = scrollView.contentOffset.y / cell_height;

    NSInteger a = (NSInteger)scale;
    NSInteger b = a + 1;
    NSInteger c = (b - scale) >(scale - a) ? a : b;
    NSLog(@"%ld",c);


    if([scrollView isEqual:self.dateTableView]){
        if(c >= self.dateDataArray.count ){
            c = self.dateDataArray.count - 1;
        }
        if(c <0){
            c = 0;
        }
        _selectedDate = [self.dateDataArray objectAtIndex:c];
    }
    if([scrollView isEqual:self.timeTableView]){
        if(c >= self.timeDataArray.count ){
            c = self.timeDataArray.count - 1;
        }
        if(c <0){
            c = 0;
        }
        _selectedTime = [self.timeDataArray objectAtIndex:c];
    }

    [UIView animateWithDuration:0.3 animations:^{
        scrollView.contentOffset = CGPointMake(0, c * cell_height);
    }];


    if(self.delegate && [self.delegate respondsToSelector:@selector(dateSelectionView:updateSelectedDate:updateSelectedTime:)]){
        [self.delegate dateSelectionView:self updateSelectedDate:_selectedDate updateSelectedTime:_selectedTime];
    }
}
-(void)setSelectedDate:(NSString *)selectedDate{
    _selectedDate = selectedDate;
}
-(void)setSelectedTime:(NSString *)selectedTime{
    _selectedTime = selectedTime;
}
-(void)layoutSubviews{
    [super layoutSubviews];

}

@end
